package action;

import global.Constants;
import global.beanUtils.BeanUtils;
import global.security.SessionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.DocumentService;
import util.FileUtils;
import util.MessageUtils;
import util.ServletHelp;
import util.StringUtils;
import domain.Document;

/**
 * 文档Action类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class DocumentAction extends BaseAction {
	/**
	 * 文档Service
	 * */
	private DocumentService documentService = null;

	/**
	 * @param documentService
	 *            the documentService to set
	 */
	public void setDocumentService(DocumentService documentService) {
		this.documentService = documentService;
	}

	/**
	 * 获取文档列表带分页
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward queryForPaging(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数设定
		Map map = request.getParameterMap();
		Document paramDocument = new Document();
		BeanUtils.populate(paramDocument, map);
		int parentId = Integer.parseInt(request.getParameter("documentId"));

		String go = request.getParameter("go");
		// 封装参数对象
		if(StringUtils.isNotEmpty(go) && go.equals("prev")){
			Document currentDocument = documentService.selectByPrimaryKey(parentId);
			if(null != currentDocument){
				parentId = currentDocument.getParentId();
			}
		}

		// 取得文档列表
		List<Document> documentList = new ArrayList<Document>();
		JSONArray datas = new JSONArray();
		paramDocument.setDocumentId(null);
		paramDocument.setParentId(parentId);
		documentList = documentService.selectByCriteriaForPaging(paramDocument);
		if(null != documentList){
			datas = JSONArray.fromObject(documentList);
		}
		int count = documentService.countByCriteria(paramDocument);

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("datas", datas);
		res.put("results", count);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 获得当前文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward getDocument(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 返回结果
		JSONObject res = new JSONObject();
		// 获得参数
		String documentId = request.getParameter("documentId");
		if(StringUtils.isNotEmpty(documentId)){
			Document document = documentService.selectByPrimaryKey(Integer.parseInt(documentId));
			if(null != document){
				res = JSONObject.fromObject(document);
			}
		}
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 获得父文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward getPrevDocument(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 返回结果
		JSONObject res = new JSONObject();
		// 获得参数
		String documentId = request.getParameter("documentId");
		if(StringUtils.isNotEmpty(documentId)){
			Document document = documentService.selectByPrimaryKey(Integer.parseInt(documentId));
			if(null != document){
				Document prevDocument = new Document();
				if(document.getParentId()==0){
					prevDocument.setDocumentId(0);
					prevDocument.setDocumentName("我的文档");
				}else{
					prevDocument = documentService.selectByPrimaryKey(document.getParentId());
				}
				if(null != prevDocument){
					res = JSONObject.fromObject(prevDocument);
				}
			}
		}
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 获得笔记分类树
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward getDocumentTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数
		String parentId = request.getParameter("parentId");
		JSONArray res = documentService.selectDocumentForTree(parentId);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 新建/修改目录
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 返回结果
		JSONObject res = new JSONObject();

		// 获得参数
		String documentId = request.getParameter("documentId");
		String documentName = request.getParameter("documentName");
		String parentId = request.getParameter("parentId");
		String isleaf = request.getParameter("isleaf");
		
		// 封装对象
		Document document = new Document();
		if(StringUtils.isNotEmpty(documentId)){
			document.setDocumentId(Integer.parseInt(documentId));
		}
		if(StringUtils.isNotEmpty(documentName)){
			document.setDocumentName(documentName);
		}
		if(StringUtils.isNotEmpty(parentId)){
			document.setParentId(Integer.parseInt(parentId));
		}
		if(StringUtils.isNotEmpty(isleaf)){
			document.setIsleaf(isleaf);
		}
		document.setStatus(Constants.STATUS_1);

		// 验证文件夹名称
		Document paramDocument = new Document();
		paramDocument.setParentId(Integer.parseInt(parentId));
		// 取得文档列表
		List<Document> documentList = new ArrayList<Document>();
		documentList = documentService.selectByCriteriaForPaging(paramDocument);
		if(null!=documentList){
			for (Document tempDocument : documentList) {
				if(tempDocument.getDocumentName().equals(documentName) && tempDocument.getIsleaf().equals(isleaf)){
					res.put("success", false);
					res.put("message", MessageUtils.setParamMessage(Constants.E_DITTO_FOLDER, new String[]{documentName}));
					ServletHelp.outRequestForJson(request, response, res.toString());
					return null;
				}
			}
		}

		// 保存
		if (StringUtils.isNotEmpty(documentId)) {
			// 更新文档
			documentService.update(document);
		} else {
			// 添加文档
			documentService.insert(document);
		}

		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 移动文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward move(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获得参数
		String documentIds = request.getParameter("documentIds");
		String parentId = request.getParameter("parentId");

		// 移动
		if (StringUtils.isNotEmpty(documentIds) && StringUtils.isNotEmpty(parentId)) {
			documentService.move(documentIds, parentId);
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 删除文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 上传文件的保存路径
		String uploadFilePath = ServletHelp.getRealPath(request,
				MessageUtils.setParamMessage(Constants.UPLOAD_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
		// 文档ID
		String documentIds = request.getParameter("documentIds");
		// 删除文档
		if (StringUtils.isNotEmpty(documentIds)) {
			documentService.delete(documentIds, uploadFilePath);
		}
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 上传文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 用户ID
		String userId = request.getParameter("userId");
		// 类别
		String documentId = request.getParameter("documentId");
		// 上传文件的保存路径
		String uploadFilePath = ServletHelp.getRealPath(request,
				MessageUtils.setParamMessage(Constants.UPLOAD_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items = null;
		// 得到所有的文件：
		items = (List) upload.parseRequest(request);
		if (StringUtils.isNotEmpty(documentId) && null != items) {
			Iterator it = items.iterator();
			while (it.hasNext()) {
				// 依次处理每一个文件：
				FileItem fi = (FileItem) it.next();
				if (Constants.UPLOAD_FILE_PARAM_NAME.equals(fi.getFieldName())) {
					String fileUUID = FileUtils.getUUID();
					String fileType = FileUtils.getFileTypeByName(fi.getName());
					String link = uploadFilePath + "/" + fileUUID+"."+fileType;

					// 文件保存到磁盘
					FileUtils.writeFileToDisk(fi.get(), link);	
					
					// 封装图片对象
					Document document = new Document();
					document.setDocumentName(FileUtils.getFileName(fi.getName()));
					document.setLink(fileUUID+"."+fileType);
					document.setType(FileUtils.getFileTypeByName(fi.getName()));
					document.setSize((int)fi.getSize());
					document.setTags("");
					document.setParentId(Integer.parseInt(documentId));
					document.setIsleaf("1");
					document.setStatus(Constants.STATUS_1);
					document.setDelflag(Constants.DEL_FLAG_1);
					document.setCreateUser(userId);
					document.setUpdateUser(userId);
					// 添加图片
					documentService.insert(document);
				}
			}
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 下载文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward downloadDocument(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String documentId = request.getParameter("documentId");
		if(StringUtils.isNotEmpty(documentId)){
			// 取得文档
			Document document = documentService.selectByPrimaryKey(Integer.parseInt(documentId));
			if(null != document){
				// 文件目录路径
				String filePath = ServletHelp.getRealPath(request,
						MessageUtils.setParamMessage(Constants.UPLOAD_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
				String url = filePath + "/" + document.getLink();
				String fileName = document.getDocumentName() + "." + document.getType();
				
				// 下载文件
				ServletHelp.download(mapping, form, request, response, url, fileName);
			}
		}
		return null;
	}
	
	/**
	 * 打包下载文档
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward downloadDocumentZip(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String documentIdStrs = request.getParameter("documentIds");
		if(StringUtils.isNotEmpty(documentIdStrs)){
			String[] documentIds = documentIdStrs.split(","); 
			int length = documentIds.length;
			String[] urls = new String[length];
			String[] fileNames = new String[length];
			// 文件目录路径
			String filePath = ServletHelp.getRealPath(request,
					MessageUtils.setParamMessage(Constants.UPLOAD_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
			for(int i=0;i<length;i++){
				// 取得文档
				Document document = documentService.selectByPrimaryKey(Integer.parseInt(documentIds[i]));
				if(null != document){
					String url = filePath + "/" + document.getLink();
					String fileName = document.getDocumentName() + "." + document.getType();
					urls[i] = url;
					fileNames[i] = fileName;
				}
			}
			
			// 打包下载文件
			ServletHelp.downloadZip(mapping, form, request, response, urls, fileNames);
		}
		return null;
	}
}
